from django.shortcuts import render,redirect
from django.http import HttpResponse
from common.models import Goods,Types
from django.core.urlresolvers import reverse
from datetime import datetime
from django.core.paginator import Paginator
from PIL import Image
import time,os
#浏览
def index(request,pindex=1):
	if pindex == '' or int(pindex)<=0:
		pindex="1"
	pindex=int(pindex)
	#获取Goods信息
	_list=Goods.objects.all()
	pageData=Paginator(_list,6)
	list=pageData.page(pindex)
	for i in list:
		tp=Types.objects.get(id=i.typeid)
		i.typename=tp.name
	plist=pageData.page_range
	context={'goodsList':list,'plist':plist,'pageCount':pageData.num_pages,'pindex':pindex}
	return render(request,'myadmin/goods/index.html',context)

#添加页面
def add(request):
	#获取商品类别信息
	tlist=Types.objects.extra(select={'_has':'concat(path,id)'}).order_by('_has')
	context={'typelist':tlist}
	return render(request,'myadmin/goods/add.html',context)

#添加操作
def insert(request):
    '''执行添加'''
    try:
        # 图片的上传处理
        myfile = request.FILES.get("pic",None)
        if not myfile:
            return HttpResponse("没有上传文件信息")
        filename = str(time.time())+"."+myfile.name.split('.').pop()
        destination = open("./static/myadmin/img/goods/"+filename,"wb+")
        for chunk in myfile.chunks():      # 分块写入文件  
            destination.write(chunk)  
        destination.close()

        # 图片的缩放
        im = Image.open("./static/myadmin/img/goods/"+filename)
        # 缩放到375*375(缩放后的宽高比例不变):
        im.thumbnail((375, 375)) 
        im.save("./static/myadmin/img/goods/"+filename,None)
        
        im = Image.open("./static/myadmin/img/goods/"+filename)
        # 缩放到220*220(缩放后的宽高比例不变):
        im.thumbnail((220,220)) 
        im.save("./static/myadmin/img/goods/m_"+filename,None)

        im = Image.open("./static/myadmin/img/goods/"+filename)
        # 缩放到75*75(缩放后的宽高比例不变):
        im.thumbnail((75, 75)) 
        im.save("./static/myadmin/img/goods/s_"+filename,None)

        #保存商品信息
        ob = Goods()
        ob.goods = request.POST['goods']
        ob.typeid = request.POST['typeid']
        ob.company = request.POST['company']
        ob.price = request.POST['price']
        ob.store = request.POST['store']
        ob.content = request.POST['content']
        ob.picname = filename
        ob.state = 1
        ob.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context={"info":"添加成功！"}
    except Exception as err:
        print(err)
        context={"info":"添加失败"}
    return render(request,"myadmin/info.html",context)

#删除
def delete(request,gid):
	try:
		userObj=Goods.objects.get(id=gid)
		userObj.delete()		
		pindex =1
		return redirect(reverse('myadmin_goods_index',args=(pindex,)))
	except Exception as e:
		content={'info':'删除失败：：'+str(e)}
		return render(request,'myadmin/info.html',content)

#编辑页面
def edit(request,gid):
	try:
		userObj=Goods.objects.get(id=gid)
		typelist=Types.objects.extra(select={'_has':'concat(path,id)'}).order_by('_has')
		content={"goods":userObj,"typelist":typelist}
		return render(request,'myadmin/goods/edit.html',content)
	except Exception as e:
		content={'info':'查询用户详情失败：：'+str(e)}
		return render(request,'myadmin/info.html',content)


# 执行商品类别信息编辑
def update(request,gid):
    try:
        b = False
        oldpicname = request.POST['oldpicname']
        if None != request.FILES.get("pic"):
            myfile = request.FILES.get("pic", None)
            if not myfile:
                return HttpResponse("没有上传文件信息！")
            # 以时间戳命名一个新图片名称
            filename = str(time.time())+"."+myfile.name.split('.').pop()
            destination = open(os.path.join("./static/myadmin/img/goods/",filename),'wb+')
            for chunk in myfile.chunks():      # 分块写入文件  
                destination.write(chunk)  
            destination.close()
            # 执行图片缩放
            im = Image.open("./static/myadmin/img/goods/"+filename)
            # 缩放到375*375:
            im.thumbnail((375, 375))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/myadmin/img/goods/"+filename, 'jpeg')
            # 缩放到220*220:
            im.thumbnail((220, 220))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/myadmin/img/goods/m_"+filename, 'jpeg')
            # 缩放到75*75:
            im.thumbnail((75, 75))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/myadmin/img/goods/s_"+filename, 'jpeg')
            b = True
            picname = filename
        else:
            picname = oldpicname
        ob = Goods.objects.get(id=gid)
        ob.goods = request.POST['goods']
        ob.typeid = request.POST['typeid']
        ob.company = request.POST['company']
        ob.price = request.POST['price']
        ob.store = request.POST['store']
        ob.content = request.POST['content']
        ob.picname = picname
        ob.state = request.POST['state']
        ob.save()
        context = {'info':'修改成功！'}
        if b:
            os.remove("./static/myadmin/img/goods/m_"+oldpicname)  
            os.remove("./static/myadmin/img/goods/s_"+oldpicname)  
            os.remove("./static/myadmin/img/goods/"+oldpicname)
    except Exception as err:
        context = {'info':'修改失败！::::::'+str(err)}
        if b:
            os.remove("./static/goods/m_"+picname) #执行新图片删除  
            os.remove("./static/goods/s_"+picname) #执行新图片删除  
            os.remove("./static/goods/"+picname) #执行新图片删除  
    return render(request,"myadmin/info.html",context)


def editByueidtor(request,gid):
	context={'gid':gid}
	return render(request,"myadmin/goods/uditorEdit.html",context)

# 执行商品类别信息编辑
def update_ueditor(request,gid):
    try:
        ob = Goods.objects.get(id=gid)
        ob.content = request.POST['content']
        ob.save()
        content={'info':'更改内容成功！！：：'}
        return render(request,'myadmin/info.html',content)
    except Exception as err:
        context = {'info':'修改失败！::::::'+str(err)}
    return render(request,"myadmin/info.html",context)